package com.linran.poll.service.lock;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Callable;

@Slf4j
public class LockPullTask implements Callable<String> {
    /*方式二：通过Object.wait()阻塞拉取任务的线程,等到数据发生变更时,再将其唤醒,这样就不会像前面的while死循环那样浪费CPU资源了,而且通知也足够及时*/
    @Getter
    @Setter
    private String data;
    private Object lock;

    public LockPullTask(Object lock) {
        this.lock = lock;
    }

    @Override
    public String call() throws Exception {
        log.info("长轮询任务开启:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        /*首先拿到lock对象锁*/
        while (StringUtils.isEmpty(data)) {
            synchronized (lock) {
                //等待
                lock.wait();
            }
        }
        log.info("长轮询任务结束:{}", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        return data;
    }
}
